/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.core.expand.spring;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.ksplatform.common.util.SystemStatu;
import cn.com.ksplatform.common.util.SystemUtil;
import cn.com.ksplatform.core.context.PlatformContext;
/**
 * 自定义Spring上下文监听器
 * 
 * 项目启动时 获取上下文并加载
 * 
 * SpringListener
 * 
 * 2015年3月17日 下午5:00:03
 * @author Mr.Xiao
 * @version 1.0.0
 *
 */
public class SpringListener extends ContextLoaderListener  implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		super.contextInitialized(arg0);
		SpringContext context =  (SpringContext) WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
		PlatformContext.SPRING_CONTEXT = context;
		callInitialized(context);
	}
	
	public void callInitialized(SpringContext context){
		String[] names = context.getBeanNamesForType(KsInitialized.class);
		for(String name : names){
			Object obj = context.getBean(name);
			try {
				obj.getClass().getMethod("initialized").invoke(obj);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void customizeContext(ServletContext arg0,
			ConfigurableWebApplicationContext arg1) {
		//读取系统安装状态
		PlatformContext.CONTEXT_PATH = arg0.getContextPath();
		String[] configs = (String[]) ArrayUtils.add(arg1.getConfigLocations(), "classpath:step-core.xml");
		arg1.setConfigLocations(configs);
		
		if(SystemUtil.existsBoot(arg0.getContextPath())){
			PlatformContext.SYSTEMSTATU = SystemStatu.INSTALLED;
		}else{
			PlatformContext.SYSTEMSTATU = SystemStatu.NOT_INSTALL;
		}
		//如果  已安装则
			//核心底层配置文件加载
			//系统状态设置为已安装
		//未安装
			//系统状态设置为未安装
		
		//arg1.setConfigLocation("classpath:core/core.xml");
		super.customizeContext(arg0, arg1);
	}
}
